package com.ruoyi.infoCandidateScores.controller;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.ruoyi.infoCandidateScores.mapper.InfoCandidateScoresMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.infoCandidateScores.domain.InfoCandidateScores;
import com.ruoyi.infoCandidateScores.service.IInfoCandidateScoresService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * (一分一段)Controller
 * 
 * @author ruoyi
 * @date 2024-04-12
 */
@RestController
@RequestMapping("/infoCandidateScores/scores")
public class InfoCandidateScoresController extends BaseController
{
    @Autowired
    private IInfoCandidateScoresService infoCandidateScoresService;

    @Autowired
    private InfoCandidateScoresMapper infoCandidateScoresMapper;

    /**
     * 查询(一分一段)列表
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoCandidateScores infoCandidateScores)
    {
        startPage();
        List<InfoCandidateScores> list = infoCandidateScoresService.selectInfoCandidateScoresList(infoCandidateScores);
        return getDataTable(list);
    }

    /**
     * 导出(一分一段)列表
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:export')")
    @Log(title = "(一分一段)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoCandidateScores infoCandidateScores)
    {
        List<InfoCandidateScores> list = infoCandidateScoresService.selectInfoCandidateScoresList(infoCandidateScores);
        ExcelUtil<InfoCandidateScores> util = new ExcelUtil<InfoCandidateScores>(InfoCandidateScores.class);
        util.exportExcel(response, list, "(一分一段)数据");
    }

    /**
     * 获取(一分一段)详细信息
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(infoCandidateScoresService.selectInfoCandidateScoresById(id));
    }

    /**
     * 新增(一分一段)
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:add')")
    @Log(title = "(一分一段)", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoCandidateScores infoCandidateScores)
    {
        return toAjax(infoCandidateScoresService.insertInfoCandidateScores(infoCandidateScores));
    }

    /**
     * 修改(一分一段)
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:edit')")
    @Log(title = "(一分一段)", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoCandidateScores infoCandidateScores)
    {
        return toAjax(infoCandidateScoresService.updateInfoCandidateScores(infoCandidateScores));
    }

    /**
     * 删除(一分一段)
     */
    @PreAuthorize("@ss.hasPermi('infoCandidateScores:scores:remove')")
    @Log(title = "(一分一段)", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(infoCandidateScoresService.deleteInfoCandidateScoresByIds(ids));
    }

    /**
     * 导入一份一段数据
     * @param file
     * @return
     */
    @PostMapping("/import")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult exportOne(MultipartFile file){
        try {
            //获取输入流
            InputStream inputStream = file.getInputStream();
            //创建read对象
            ExcelReaderBuilder read = EasyExcel.read(inputStream);
            //设置文件格式
            read.excelType(ExcelTypeEnum.XLSX);
            //自动关闭流
            read.autoCloseStream(true);
            //创建监听器
            read.registerReadListener(new AnalysisEventListener<Map<Integer, String>>() {
                //文科
                private List<InfoCandidateScores> wenkeList = new ArrayList<>();
                //理科
                private List<InfoCandidateScores> likeList = new ArrayList<>();
                private String year;


                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    //获取表头年份
                    String s = headMap.get(0);
                    String substring = s.substring(0, 4);
                    year = substring;
                    System.out.println(year);
                }

                @Override
                public void invoke(Map<Integer, String> originalMap, AnalysisContext analysisContext) {
                    Map<Integer, String> firstMap = originalMap.entrySet().stream()
                            .filter(entry -> entry.getKey() < 3 && entry.getValue() != null)
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

                    Map<Integer, String> secondMap = originalMap.entrySet().stream()
                            .filter(entry -> entry.getKey() >= 3 && entry.getValue() != null)
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
//                    System.out.println(firstMap);
                    String jsonString = JSON.toJSONString(firstMap);

                    if (firstMap.size() == 3 && !firstMap.get(0).equals("序号")){
                        InfoCandidateScores scores = new InfoCandidateScores();
                        scores.setHighExamScore(new BigDecimal(firstMap.get(1)));
                        scores.setRegionNubmer(Long.valueOf(firstMap.get(2)));
                        scores.setSubjectType(1l);
                        scores.setHighExamYear(year);
                        if (firstMap.get(0).equals("1")){
                            scores.setScoreNumber(Long.valueOf(firstMap.get(2)));
                            scores.setRankRegion("1-"+firstMap.get(2));
                        }else {
                            Long regionNubmer = likeList.get(likeList.size() - 1).getRegionNubmer();
                            scores.setScoreNumber(Long.valueOf(firstMap.get(2))-regionNubmer);
                            scores.setRankRegion(regionNubmer+1+"-"+firstMap.get(2));
                        }
                        likeList.add(scores);
                    }
                    if (secondMap.size() == 3 &&!firstMap.get(0).equals("序号")){
                        InfoCandidateScores scores = new InfoCandidateScores();
                        scores.setHighExamScore(new BigDecimal(secondMap.get(4)));
                        scores.setRegionNubmer(Long.valueOf(secondMap.get(5)));
                        scores.setHighExamYear(year);
                        if (firstMap.get(0).equals("1")){
                            //获取序号为1的条目
                            //存
                            scores.setScoreNumber(Long.valueOf(secondMap.get(5)));
                            //排位区间当前分数人数-上级分数人数=当前排位区间人数
                            scores.setRankRegion("1-"+secondMap.get(5));
                        }else {
                            Long regionNubmer = wenkeList.get(wenkeList.size() - 1).getRegionNubmer();
                            scores.setScoreNumber(Long.valueOf(secondMap.get(5))-regionNubmer);
                            scores.setRankRegion(regionNubmer+1+"-"+secondMap.get(5));
                        }
                        scores.setSubjectType(2l);
                        wenkeList.add(scores);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    infoCandidateScoresMapper.insertInfoCandidateScoresList(likeList);
                    infoCandidateScoresMapper.insertInfoCandidateScoresList(wenkeList);
                    System.out.println("读取完毕");

                }
            });
            ExcelReader build = read.build();
            build.readAll();
            build.finish();
            //根据文件流获取Excel

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return AjaxResult.success();

    }
}
